package org.example.projecttwo.service.Impl.message;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.common.util.StringUtils;
import org.example.projecttwo.entity.Message;
import org.example.projecttwo.mapper.MessageMapper;
import org.example.projecttwo.service.Imessage.IMessageService;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 消息表 服务实现类
 * </p>
 *
 * @author nn
 * @since 2025-11-01
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Override
    public IPage<Message> pageBy(Page<Message> page, Integer status, Integer targetScope, String keyword, String startTime, String endTime) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();

        //根据状态筛选
        if (status != null){
            queryWrapper.eq(Message::getStatus, status);
        }

        //根据接收范围筛选
        if (targetScope != null){
            queryWrapper.eq(Message::getTargetScope, targetScope);
        }

        //根据关键词筛选
        if (keyword != null){
            queryWrapper.like(Message::getContent, keyword);
        }

        //根据时间范围筛选
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
            try{
                //转换为时间戳
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date startDate = sdf.parse(startTime+ "00:00:))");
                Date endDate = sdf.parse(endTime+ "23:59:59");
                queryWrapper.between(Message::getCreateTime, startDate, endDate);
            }catch (ParseException e){
                log.error("时间转换错误", e);
            }
        }

        return this.page(page, queryWrapper);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Message newMessage = new Message();
        newMessage.setId(id);
        newMessage.setStatus(status);
        this.updateById(newMessage);
    }

    @Override
    public void batchUpdateStatus(List<Long> ids, Integer status) {
        if (CollectionUtils.isEmpty(ids)){
            return;
        }

        LambdaUpdateWrapper<Message> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(Message::getId, ids);
        wrapper.set(Message::getStatus, status);
        this.update(wrapper);
    }
}
